package com.qiguliuxing.dts.admin.controller;

import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.domain.DtsCategory;
import com.qiguliuxing.dts.service.base.DtsCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/category")
@Validated
@Api(tags = ApiAdminConsts.Category.PARENT)
public class AdminCategoryController {
	private static final Logger logger = LoggerFactory.getLogger(AdminCategoryController.class);

	@Autowired
	private DtsCategoryService categoryService;

	@RequiresPermissions("admin:category:list")
	@RequiresPermissionsDesc(menu = { "商场管理", "类目管理" }, button = "查询")
	@ApiOperation(value = ApiAdminConsts.Category.LIST)
	@GetMapping("/list")
	@WebLog(description = ApiAdminConsts.Category.LIST, excludes = {LogParamsConsts.RESPONSE})
	public Object list(@ApiParam(value = "类目id") String id,
					   @ApiParam(value = "类目名称") String name,
					   @ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
					   @ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
					   @ApiParam(value = "排序字段",defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
					   @ApiParam(value = "排序规则",defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
		List<DtsCategory> collectList = categoryService.querySelective(id, name, page, limit, sort, order);
		long total = PageInfo.of(collectList).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", collectList);
		return ResponseUtils.ok(data);
	}

	private Object validate(DtsCategory category) {
		String name = category.getName();
		if (StringUtils.isEmpty(name)) {
			return ResponseUtils.badArgument();
		}

		String level = category.getLevel();
		if (StringUtils.isEmpty(level)) {
			return ResponseUtils.badArgument();
		}
		if (!"L1".equals(level) && !"L2".equals(level)) {
			return ResponseUtils.badArgumentValue();
		}

		Integer pid = category.getPid();
		if ("L2".equals(level) && (pid == null)) {
			return ResponseUtils.badArgument();
		}

		return null;
	}

	@RequiresPermissions("admin:category:create")
	@RequiresPermissionsDesc(menu = { "商场管理", "类目管理" }, button = "添加")
	@ApiOperation(value = ApiAdminConsts.Category.CREATE)
	@PostMapping("/create")
	@WebLog(description = ApiAdminConsts.Category.CREATE, persistence = true)
	public Object create(@RequestBody DtsCategory category) {
		Object error = validate(category);
		if (error != null) {
			return error;
		}
		categoryService.add(category);
		return ResponseUtils.ok(category);
	}

	@RequiresPermissions("admin:category:read")
	@RequiresPermissionsDesc(menu = { "商场管理", "类目管理" }, button = "详情")
	@GetMapping("/read")
	public Object read(@ApiParam(value = "类目id") @NotNull Integer id) {
		DtsCategory category = categoryService.findById(id);
		return ResponseUtils.ok(category);
	}

	@RequiresPermissions("admin:category:update")
	@RequiresPermissionsDesc(menu = { "商场管理", "类目管理" }, button = "编辑")
	@ApiOperation(value = ApiAdminConsts.Category.UPDATE)
	@PostMapping("/update")
	@WebLog(description = ApiAdminConsts.Category.UPDATE, persistence = true)
	public Object update(@RequestBody DtsCategory category) {
		Object error = validate(category);
		if (error != null) {
			return error;
		}

		if (categoryService.updateById(category) == 0) {
			logger.error("商场管理->类目管理->编辑 失败，更新数据失败！");
			return ResponseUtils.updatedDataFailed();
		}
		return ResponseUtils.ok();
	}

	@RequiresPermissions("admin:category:delete")
	@RequiresPermissionsDesc(menu = { "商场管理", "类目管理" }, button = "删除")
	@ApiOperation(value = ApiAdminConsts.Category.DELETE)
	@PostMapping("/delete")
	@WebLog(description = ApiAdminConsts.Category.DELETE, persistence = true)
	public Object delete(@RequestBody DtsCategory category) {
		Integer id = category.getId();
		if (id == null) {
			return ResponseUtils.badArgument();
		}
		categoryService.deleteById(id);
		return ResponseUtils.ok();
	}

	@RequiresPermissions("admin:category:list")
	@ApiOperation(value = "一级分类目录查询")
	@GetMapping("/l1")
	public Object catL1() {
		// 所有一级分类目录
		List<DtsCategory> l1CatList = categoryService.queryL1();
		List<Map<String, Object>> data = new ArrayList<>(l1CatList.size());
		for (DtsCategory category : l1CatList) {
			Map<String, Object> d = new HashMap<>(2);
			d.put("value", category.getId());
			d.put("label", category.getName());
			data.add(d);
		}
		return ResponseUtils.ok(data);
	}
}
